package com.LeeCode;

/**
 * 祖父节点值为偶数的节点和
 */

public class Code1315 {
    public static void main(String[] args) {
        Integer[] arr = {6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code1315().sumEvenGrandparent(root));

    }

    public int sumEvenGrandparent(TreeNode root) {
        return dfs(root, 1, 1);
    }

    private int dfs(TreeNode root, int parent, int grandparent) {
        if (root == null) return 0;

        int count = (grandparent & 1) == 0 ? root.val : 0;

        grandparent = parent;
        parent = root.val;
        count += dfs(root.left, parent, grandparent);
        count += dfs(root.right, parent, grandparent);
        return count;
    }
}
